package com.shuda.business.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shuda.business.user.entity.RoleEntity;
import com.shuda.business.user.entity.RolePermissionEntity;
import com.shuda.business.user.mapper.RoleMapper;
import com.shuda.business.user.mapper.RolePermissionMapper;
import com.shuda.business.user.service.RoleService;
import com.shuda.common.dto.PageDTO;
import com.shuda.common.exception.BusinessException;
import com.shuda.common.security.SecurityUtils;
import com.shuda.common.utils.PageResult;
import com.shuda.common.utils.PageUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 角色服务实现类
 */
@Service
@RequiredArgsConstructor
public class RoleServiceImpl implements RoleService {

    private final RoleMapper roleMapper;
    private final RolePermissionMapper rolePermissionMapper;

    @Override
    public PageResult<RoleEntity> getRolePage(PageDTO pageDTO, QueryWrapper<RoleEntity> queryWrapper) {
        Page<RoleEntity> page = PageUtils.buildPage(pageDTO);
        Page<RoleEntity> rolePage = roleMapper.selectPage(page, queryWrapper);
        return PageUtils.buildPageResult(rolePage);
    }

    @Override
    public RoleEntity getById(Long id) {
        return roleMapper.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createRole(RoleEntity role) {
        // 检查角色编码是否已存在（对齐RoleEntity字段：roleKey作为权限字符串/编码）
        QueryWrapper<RoleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_key", role.getRoleKey());
        if (roleMapper.selectCount(queryWrapper) > 0) {
            throw new BusinessException("角色编码已存在");
        }
        
        // 设置创建信息（对齐com.shuda.common.core.domain.BaseEntity：createdTime/creator/updatedTime/updater/delFlag）
        role.setCreatedTime(LocalDateTime.now());
        role.setCreator(SecurityUtils.getCurrentUserId());
        role.setUpdatedTime(LocalDateTime.now());
        role.setUpdater(SecurityUtils.getCurrentUserId());
        role.setDelFlag("0");
        
        roleMapper.insert(role);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRole(RoleEntity role) {
        // 检查角色是否存在
        RoleEntity existingRole = roleMapper.selectById(role.getId());
        if (existingRole == null) {
            throw new BusinessException("角色不存在");
        }
        
        // 如果更新角色编码，需要检查是否已存在
        if (role.getRoleKey() != null && !role.getRoleKey().equals(existingRole.getRoleKey())) {
            QueryWrapper<RoleEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("role_key", role.getRoleKey());
            if (roleMapper.selectCount(queryWrapper) > 0) {
                throw new BusinessException("角色编码已存在");
            }
        }
        
        // 设置更新信息（对齐com.shuda.common.core.domain.BaseEntity）
        role.setUpdatedTime(LocalDateTime.now());
        role.setUpdater(SecurityUtils.getCurrentUserId());
        
        roleMapper.updateById(role);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRole(Long id) {
        RoleEntity role = roleMapper.selectById(id);
        if (role == null) {
            throw new BusinessException("角色不存在");
        }
        
        // 逻辑删除
        role.setDelFlag("2");
        role.setUpdatedTime(LocalDateTime.now());
        role.setUpdater(SecurityUtils.getCurrentUserId());
        roleMapper.updateById(role);
        
        // 删除角色权限关联
        rolePermissionMapper.deleteByRoleId(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRoles(List<Long> ids) {
        for (Long id : ids) {
            deleteRole(id);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRoleStatus(Long id, String status) {
        RoleEntity role = roleMapper.selectById(id);
        if (role == null) {
            throw new BusinessException("角色不存在");
        }
        
        role.setStatus(status);
        // 对齐BaseEntity字段命名
        role.setUpdatedTime(LocalDateTime.now());
        role.setUpdater(SecurityUtils.getCurrentUserId());
        roleMapper.updateById(role);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignPermissions(Long roleId, List<Long> permissionIds) {
        // 检查角色是否存在
        RoleEntity role = roleMapper.selectById(roleId);
        if (role == null) {
            throw new BusinessException("角色不存在");
        }
        
        // 删除原有权限关联
        rolePermissionMapper.deleteByRoleId(roleId);
        
        // 批量插入新的权限关联：构造RolePermissionEntity列表
        if (permissionIds != null && !permissionIds.isEmpty()) {
            List<RolePermissionEntity> rolePermissions = permissionIds.stream()
                    .map(pid -> {
                        RolePermissionEntity e = new RolePermissionEntity();
                        e.setRoleId(roleId);
                        e.setPermissionId(pid);
                        e.setCreateBy(SecurityUtils.getCurrentUserId());
                        e.setCreateTime(LocalDateTime.now());
                        e.setUpdateBy(SecurityUtils.getCurrentUserId());
                        e.setUpdateTime(LocalDateTime.now());
                        e.setDeleted(false);
                        return e;
                    }).toList();
            rolePermissionMapper.batchInsert(rolePermissions);
        }
    }

    @Override
    public List<Long> getRolePermissions(Long roleId) {
        // 适配Mapper方法：按角色ID列表查询权限ID
        return rolePermissionMapper.selectPermissionIdsByRoleIds(java.util.List.of(roleId));
    }

    @Override
    public List<RoleEntity> getAllRoles() {
        QueryWrapper<RoleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "active");
        // 对齐逻辑删除字段：del_flag = '0' 表示未删除
        queryWrapper.eq("del_flag", "0");
        queryWrapper.orderByDesc("create_time");
        return roleMapper.selectList(queryWrapper);
    }
}